package com.zb.service.impl;

import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.FieldTypeConstant;
import com.zb.entity.*;
import com.zb.mapper.ZjGoodsParamFieldMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjGoodsParamFieldContentService;
import com.zb.service.ZjGoodsParamFieldService;
import com.zb.service.ZjProductParamFieldValService;
import com.zb.service.ZjSpareParamFieldValService;
import com.zb.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品参数字段表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-08-01
 */
@Service
public class ZjGoodsParamFieldServiceImpl extends ServiceImpl<ZjGoodsParamFieldMapper, ZjGoodsParamField> implements ZjGoodsParamFieldService {
    @Resource
    private ZjGoodsParamFieldMapper goodsParamFieldMapper;
    @Resource
    private ZjGoodsParamFieldContentService fieldContentService;
    @Resource
    private ZjProductParamFieldValService productParamFieldValService;
    @Resource
    private ZjSpareParamFieldValService spareParamFieldValService;


    // 根据商品参数ID删除参数字段
    @Override
    @Transactional
    public void deleteByParamIds(List<Long> paramIdList) {
        if (null == paramIdList || paramIdList.isEmpty()) {
            return;
        }
        QueryWrapper<ZjGoodsParamField> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        wrapper.in("param_id", paramIdList);
        List<Long> idList = this.list(wrapper).stream().map(ZjGoodsParamField::getId).toList();
        fieldContentService.deleteByParamFieldIds(idList);
        goodsParamFieldMapper.deleteByParamIds(paramIdList);
    }

    // 新增或修改商品参数字段
    @Override
    @Transactional
    public void save(Long custAccId, GoodsParamFieldVo paramFieldVo) {
        Assert.isTrue(null == goodsParamFieldMapper.existByName(paramFieldVo.getId(), paramFieldVo.getParamId(), paramFieldVo.getName()),
                "字段名称已重复！", paramFieldVo.getName());
        if (paramFieldVo.getType().equals(FieldTypeConstant.FIELD_TYPE_3) || paramFieldVo.getType().equals(FieldTypeConstant.FIELD_TYPE_4)) {
            Assert.isTrue(!paramFieldVo.getContentVos().isEmpty(), "字段类型为'单选/多选'的字段内容至少填写一项", null);
        }

        ZjGoodsParamField paramField = new ZjGoodsParamField();
        BeanUtils.copyProperties(paramFieldVo, paramField);
        paramField.setDisabled(paramFieldVo.getStatus());
        if (null != paramField.getId()) {
            this.updateById(paramField);
            if (null != paramFieldVo.getContentIds() && !paramFieldVo.getContentIds().isEmpty()) {
                fieldContentService.removeByIds(paramFieldVo.getContentIds());
            }
            fieldContentService.save(custAccId, paramField.getId(), paramFieldVo.getContentVos());
            return;
        }
        paramField.setId(IdWorker.getId());
        paramField.setCustAccId(custAccId);
        this.save(paramField);
        fieldContentService.save(custAccId, paramField.getId(), paramFieldVo.getContentVos());
    }

    // 获取参数字段列表
    @Override
    public Map<String, Object> getParamFieldList(Long paramId, FieldSelectVo selectVo) {
        QueryWrapper<ZjGoodsParamField> wrapper = new QueryWrapper<>();
        wrapper.eq("param_id", paramId);
        wrapper.orderByDesc("gmt_update");
        if (null != selectVo.getType()) {
            wrapper.eq("type", selectVo.getType());
        }
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setPageLimit(selectVo);
        Page<ZjGoodsParamField> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);

        List<Long> paramFieldIdList = page.getRecords().stream().filter(f -> f.getType().equals(FieldTypeConstant.FIELD_TYPE_3)
                || f.getType().equals(FieldTypeConstant.FIELD_TYPE_4)).map(ZjGoodsParamField::getId).toList();
        List<ZjGoodsParamFieldContent> fieldContents = fieldContentService.getByParamFieldIds(paramFieldIdList);

        List<GoodsFieldListVo> voList = new ArrayList<>();
        page.getRecords().forEach(t -> {
            voList.add(GoodsFieldListVo.beanToVo(t,
                    fieldContents.stream().filter(ZjGoodsParamFieldContent -> ZjGoodsParamFieldContent.getParamFieldId().equals(t.getId()))
                            .map(ZjGoodsParamFieldContent::getVal).collect(Collectors.joining("、")))
            );
        });
        return PageUtil.pageList(page.getCurrent(), page .getSize(), page.getTotal(), voList);
    }

    // 获取参数字段信息
    @Override
    public GoodsFieldVo getParamFieldInfo(Long id) {
        ZjGoodsParamField paramField = this.getById(id);
        Assert.isTrue(null != paramField, "[" + id + "]的数据不存在", null);

        GoodsFieldVo vo = new GoodsFieldVo();
        BeanUtils.copyProperties(paramField, vo);
        vo.setStatus(paramField.getDisabled());

        if (Objects.equals(FieldTypeConstant.FIELD_TYPE_3, paramField.getType()) || Objects.equals(FieldTypeConstant.FIELD_TYPE_4, paramField.getType())) {
            List<GoodsFieldContentVo> contentVos = new ArrayList<>();
            fieldContentService.getByParamFieldId(id).forEach(t -> contentVos.add(new GoodsFieldContentVo(t.getId(), t.getVal())));
            vo.setContentVos(contentVos);
        }
        return vo;
    }

    // 批量禁用或启用参数字段
    @Override
    public void updateBatchDisableByIds(List<Long> idList, boolean status) {
        goodsParamFieldMapper.updateBatchDisableByIds(idList, status);
    }

    // 批量删除参数字段
    @Override
    public void deleteByIds(List<Long> idList) {
        List<Long> fieldIds = productParamFieldValService.getByGoodsParamFieldIds(idList);
        if (CollectionUtils.isNotEmpty(fieldIds)) {
            QueryWrapper<ZjGoodsParamField> wrapper = new QueryWrapper<>();
            wrapper.select("name");
            wrapper.in("id", fieldIds);
            String fieldNames = this.list(wrapper).stream().map(ZjGoodsParamField::getName).collect(Collectors.joining("、"));
            Assert.isTrue(false, "商品参数自定义字段[ " + fieldNames + " ]已被使用中，不可删除");
        }
        fieldIds = spareParamFieldValService.getByGoodsParamFieldIds(idList);
        if (CollectionUtils.isNotEmpty(fieldIds)) {
            QueryWrapper<ZjGoodsParamField> wrapper = new QueryWrapper<>();
            wrapper.select("name");
            wrapper.in("id", fieldIds);
            String fieldNames = this.list(wrapper).stream().map(ZjGoodsParamField::getName).collect(Collectors.joining("、"));
            Assert.isTrue(false, "商品参数自定义字段[ " + fieldNames + " ]已被使用中，不可删除");
        }
        fieldContentService.deleteByParamFieldIds(idList);
        this.removeByIds(idList);
    }

    // 根据参数ID获取参数字段
    @Override
    public List<SelectFieldVo> pageSelect(Long paramId) {
        QueryWrapper<ZjGoodsParamField> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("is_required", "gmt_update");
        wrapper.select("id", "name", "type", "upload_size", "upload_qty", "tip", "is_required AS required");
        wrapper.eq("param_id", paramId).eq("is_disabled", false);
        List<ZjGoodsParamField> page = this.list(wrapper);
        List<Long> fieldIds = page.stream().map(ZjGoodsParamField::getId).toList();
        List<ZjGoodsParamFieldContent> contents = fieldContentService.getByParamFieldIds(fieldIds);

        List<SelectFieldVo> voList = new ArrayList<>();
        page.forEach(t -> voList.add(new SelectFieldVo(t.getId(), t.getName(), t.getType(),
                t.getUploadSize(), t.getUploadQty(), t.getTip(), t.getRequired(),
                contents.stream().filter(ZjGoodsParamFieldContent -> ZjGoodsParamFieldContent.getParamFieldId().equals(t.getId())).map(ZjGoodsParamFieldContent::getVal).toList())));
        return voList;
    }
}
